package cn.xianshu.org.service.impl;

import cn.xianshu.basic.exception.BasicException;
import cn.xianshu.basic.query.BasicQuery;
import cn.xianshu.basic.service.impl.BasicServiceImpl;
import cn.xianshu.basic.util.PageList;
import cn.xianshu.org.domain.Employee;
import cn.xianshu.org.domain.Shop;
import cn.xianshu.org.mapper.EmployeeMapper;
import cn.xianshu.org.mapper.ShopMapper;
import cn.xianshu.org.query.ShopQuery;
import cn.xianshu.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
//@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class ShopServiceImpl extends BasicServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    @Transactional
    public void update(Shop shop) {
        shopMapper.update(shop);
    }

    @Override
    public PageList<Shop> queryList(BasicQuery query) {
        // 总条数
        Integer totals = shopMapper.count(query);
        // 当前页数据
        List<Shop> rows = shopMapper.queryData(query);
        return new PageList<>(totals, rows);

    }
   @Override
   public PageList<Shop> pageQuery(ShopQuery query) {
       // 总条数
       Integer total = shopMapper.count(query);
       // 每页显示数据
       List<Shop> rows = shopMapper.queryData(query);
       return new PageList<>(total, rows);
   }
    @Override
    public List<Shop> queryTree() {
        return shopMapper.queryTree();
    }

    @Override
    public void shopRegister(Shop shop){
        // 获取
        Employee admin = shop.getAdmin();
        // 判断两次密码是否一致双重校验  （前端后端）
        if(!admin.getPassword().equals(admin.getComfirmPassword())){
            throw new BasicException("密码不一致，请重新输入。。。");
        }
        // 用户名是否存在
        Employee employee = employeeMapper.findByUser(admin.getUsername());
        if (employee != null){
            throw new BasicException("用户已存在");
        }
        // 两张表 先添加employee，返回主键自增
        employeeMapper.insert(admin);
        // 再把employee的自增id 设置到shop中  添加shop
        shop.setAdmin(admin);
        shopMapper.insert(shop); // 返回自增id
        // 更新employee表中的shop_id 字段
        admin.setShop_id(shop.getId());
        employeeMapper.update(admin);
    }
}
